package com.zhq.security.auth.controller;


import com.google.code.kaptcha.impl.DefaultKaptcha;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.yaml.snakeyaml.scanner.Constant;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@CrossOrigin
public class LoginController {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/login")
    public String login(String username,String password){
        return  "success";
    }

    @GetMapping("test")
    public String test(String psw){
        return  passwordEncoder.encode(psw);
    }

    @PostMapping("/singLogout")
    public  String singLogout(){
        return "登出成功，请重新登录";
    }

    @ApiOperation("图形验证码")
    @GetMapping("/defaultImg")
    public Map<String,Object> generateCode(){
        Map<String,Object> map=new HashMap<>();
        ByteArrayOutputStream byteArrayOutputStream=null;
        //生成文字验证码
        String text = defaultKaptcha.createText();
        //生成图片验证码
            BufferedImage image = defaultKaptcha.createImage(text);
        byteArrayOutputStream=new ByteArrayOutputStream();
        try {
            ImageIO.write(image,"jpg",byteArrayOutputStream);

        }catch (Exception e){
            throw  new RuntimeException(e);
        }
        map.put("img", Base64.getEncoder().encodeToString(byteArrayOutputStream.toByteArray()));
        //生成验证码对应的token  以token为key  验证码为value存在redis中
        String codeToken = UUID.randomUUID().toString();
        stringRedisTemplate.opsForValue().set(text,text);
        map.put("cToken", codeToken);
        return map;
    }
}
